import React from 'react'
import {
  Form,
  Select,
  Button,
  Radio,
  DatePicker,
  List,
  Icon,
  InputNumber,
  Input,
  Checkbox,
  message,
  TimePicker
} from 'antd'
import ProjectSelect from './CreateTask/ProductSelect'
import {
  projectFindBypageApi,
  tuserFindBypageApi,
  maintaskAddApi
} from '../api/ajax'
import moment from 'moment'
import _ from 'lodash'
import { checkTime } from './Task'

const FormItem = Form.Item
const Option = Select.Option
const RadioGroup = Radio.Group

class CreateTask extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      projectSource: [],
      userSource: [],
      effStartDate: false,
      executionType: 0,
      monthType: null,
      executionMode: null,
      visible: false,
      productSource: [],
      selectedRowKeys: [],
      selectedProductData: []
    }
  }
  componentDidMount() {
    this.loadData()
  }
  loadData = () => {
    projectFindBypageApi().then(v => {
      const {
        list: { results }
      } = v
      this.setState({
        projectSource: results ? results : []
      })
    })
    tuserFindBypageApi().then(v => {
      const {
        list: { results }
      } = v
      this.setState({
        userSource: results ? results : []
      })
    })
  }
  callback = selectedRows => {
    if (!selectedRows) {
      this.setState({
        visible: false
      })
      return
    }
    this.setState({
      productSource: selectedRows,
      selectedRowKeys: selectedRows.map(i => i.id),
      selectedProductData: this.state.selectedProductData
        .filter(i => selectedRows.some(j => j.id === i.id))
        .concat(
          selectedRows
            .filter(i =>
              this.state.selectedProductData.every(j => j.id !== i.id)
            )
            .map(i => {
              let obj = {}
              obj.isSubFile = 1
              obj.id = i.id
              return obj
            })
        ),
      visible: false
    })
  }
  save = () => {
    const { validateFields } = this.props.form
    validateFields((errors, values) => {
      if (errors) return
      if (
        !this.state.selectedProductData ||
        this.state.selectedProductData.length === 0
      ) {
        message.error('源产品信息不得为空！')
        return
      }
      if (
        values.aimsIds.length > 1 &&
        this.state.selectedProductData.length > 1
      ) {
        message.error('源产品信息与目标信息不能同时选中多个！')
        return
      }
      if (
        values.executionMode == 2 &&
        _.isString(values.timeList) &&
        !checkTime(values.timeList)
      ) {
        message.error('执行多次(无规律)时间格式错误')
        return
      }
      let obj = {}
      obj.effectiveTime = values.effectiveTime
      obj.executionType = values.executionType
      obj.executionMode =
        values.executionMode == null ? 3 : values.executionMode
      obj.monthType = values.monthType
      obj.monthDay = values.monthDay
      obj.projectId = values.projectId
      obj.startDate = values.startDate
      obj.timeList = values.timeList
      // obj.taskCode = values.taskCode
      obj.updateType = values.updateType
      obj.aimsIds = values.aimsIds.join(',')
      obj.sourceId = JSON.stringify(this.state.selectedProductData)
      if (values.exStartDate) obj.exStartDate = values.exStartDate

      if (values.exEndDate) obj.exEndDate = values.exEndDate

      if (values.effectiveTime === 2) {
        obj.effStartDate = values.effStartDate[0]
        obj.effEndDate = values.effStartDate[1]
      }
      // if (values.taskCode) obj.taskCode = values.taskCode
      if (values.timeNum) obj.timeNum = values.timeNum
      if (values.timeType) obj.timeType = values.timeType
      if (values.week) obj.week = values.week.join(',')
      if (
        obj.exStartDate &&
        obj.exEndDate &&
        moment(obj.exEndDate).hour() <= moment(obj.exStartDate).hour()
      ) {
        message.error('任务执行点，截止小时数不能大于开始小时！')
        return
      }
      maintaskAddApi(obj).then(v => {
        message.success('保存成功')
        this.props.history.push('task')
      })
      // this.setState({ confirmLoading: true })
      // if (errors) {
      // } else {
      // }
      // this.props.history.goBack()
    })
  }
  render() {
    const { getFieldDecorator, setFieldsValue } = this.props.form
    const { history } = this.props
    const { projectSource } = this.state
    const rules = {
      rules: [
        {
          required: true,
          message: '字符不得为空'
        }
      ]
    }
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px'
    }
    return (
      <div className="createTask">
        {this.state.visible && (
          <ProjectSelect
            visible={this.state.visible}
            callback={this.callback}
            selectedRowKeys={this.state.selectedRowKeys}
          />
        )}
        <Form layout="inline">
          <h3>任务信息</h3>
          <div className="createTask-row">
            <FormItem label="项目名称">
              {getFieldDecorator('projectId', rules)(
                <Select style={{ width: '176px' }} placeholder="请选择">
                  {projectSource.map(v => (
                    <Option key={v.id}>{v.projectName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
            {/* <FormItem label="任务编号">
              {getFieldDecorator('taskCode', rules)(<Input />)}
            </FormItem> */}
          </div>
          <div className="createTask-row">
            <FormItem label="文件更新方式">
              {getFieldDecorator('updateType', rules)(
                <RadioGroup>
                  <Radio style={radioStyle} value={1}>
                    增量（只更新上个执行时间点以后的文件）
                  </Radio>
                  <Radio style={radioStyle} value={2}>
                    差异（更新源地址有、而目标地址无的文件）
                  </Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem label="开始文件时间">
              {getFieldDecorator('startDate', rules)(
                <DatePicker
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                />
              )}
            </FormItem>
          </div>
          <h3>源产品信息</h3>
          <div className="createTask-row">
            <List
              itemLayout="horizontal"
              dataSource={this.state.productSource.map(p => {
                p.title = p.productName
                return p
              })}
              renderItem={item => (
                <List.Item>
                  <div>
                    <span style={{ color: '#000' }}>
                      <span style={{ marginRight: '100px' }}>{item.title}</span>
                      是否包括子文件夹中源产品: &nbsp; &nbsp; &nbsp; &nbsp;
                      &nbsp;
                      <RadioGroup
                        onChange={e => {
                          this.setState({
                            selectedProductData: this.state.selectedProductData.map(
                              p => {
                                if (p.id === item.id) {
                                  p.isSubFile = e.target.value
                                }
                                return p
                              }
                            )
                          })
                        }}
                        defaultValue={1}
                      >
                        <Radio value={1}>是</Radio>
                        <Radio value={2}>否</Radio>
                      </RadioGroup>
                    </span>
                    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                    &nbsp; &nbsp;
                    <span
                      style={{ cursor: 'pointer' }}
                      onClick={() => {
                        this.setState({
                          selectedRowKeys: _.remove(
                            this.state.selectedRowKeys,
                            function(s) {
                              return s !== item.id
                            }
                          ),
                          selectedProductData: _.remove(
                            this.state.selectedProductData,
                            function(s) {
                              return s.id !== item.id
                            }
                          ),
                          productSource: _.remove(
                            this.state.productSource,
                            function(s) {
                              return s.id !== item.id
                            }
                          )
                        })
                      }}
                    >
                      <Icon
                        type="delete"
                        theme="twoTone"
                        style={{ fontSize: '20px' }}
                      />
                    </span>
                  </div>
                </List.Item>
              )}
            />
          </div>
          <div className="createTask-row">
            <Button
              icon="plus-circle"
              onClick={() => this.setState({ visible: true })}
            >
              继续添加源产品
            </Button>
          </div>

          <h3>目标信息</h3>
          <div className="createTask-row">
            <FormItem label="目标名称（可多选）">
              {getFieldDecorator('aimsIds', rules)(
                <Select
                  mode="multiple"
                  style={{ width: '400px' }}
                  placeholder="请选择"
                >
                  {this.state.userSource.map(user => {
                    return <Option key={user.id}>{user.userName}</Option>
                  })}
                </Select>
              )}
            </FormItem>
          </div>

          <h3>触发器</h3>
          <div className="createTask-row">
            <div>
              <FormItem label="任务有效时间段">
                {getFieldDecorator('effectiveTime', rules)(
                  <RadioGroup
                    onChange={e => {
                      if (e.target.value === 2) {
                        this.setState({
                          effStartDate: true
                        })
                      } else {
                        this.setState({
                          effStartDate: false
                        })
                      }
                    }}
                  >
                    <Radio value={1}>永久</Radio>
                    <Radio value={2}>自定义</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              {this.state.effStartDate && (
                <FormItem>
                  {getFieldDecorator('effStartDate', rules)(
                    <DatePicker.RangePicker />
                  )}
                </FormItem>
              )}
            </div>
            <div>
              <FormItem label="任务执行时点">
                {getFieldDecorator('executionType', rules)(
                  <RadioGroup
                    onChange={e => {
                      this.setState({
                        executionType: e.target.value,
                        executionMode: null
                      })
                      setFieldsValue({ executionMode: null })
                    }}
                  >
                    <Radio value={1}>每天</Radio>
                    <Radio value={2}>每周</Radio>
                    <Radio value={4}>每月</Radio>
                    <Radio value={3}>实时</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              {this.state.executionType === 2 && (
                <div>
                  <FormItem label="指定">
                    {getFieldDecorator('week', rules)(
                      <Checkbox.Group style={{ width: '100%' }}>
                        <Checkbox value="1">周一</Checkbox>
                        <Checkbox value="2">周二</Checkbox>
                        <Checkbox value="3">周三</Checkbox>
                        <Checkbox value="4">周四</Checkbox>
                        <Checkbox value="5">周五</Checkbox>
                        <Checkbox value="6">周六</Checkbox>
                        <Checkbox value="7">周日</Checkbox>
                      </Checkbox.Group>
                    )}
                  </FormItem>
                </div>
              )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) && (
                <div>
                  <FormItem label="执行方式">
                    {getFieldDecorator('executionMode', rules)(
                      <RadioGroup
                        onChange={e =>
                          this.setState({
                            executionMode: e.target.value
                          })
                        }
                      >
                        <Radio value={0}>执行一次</Radio>
                        <Radio value={1}>执行多次(有规律)</Radio>
                        <Radio value={2}>执行多次(无规律)</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                </div>
              )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) &&
                this.state.executionMode === 0 && (
                  <div>
                    <FormItem label="开始时间">
                      {getFieldDecorator('exStartDate', rules)(
                        <TimePicker format="HH:mm" />
                      )}
                    </FormItem>
                  </div>
                )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) &&
                this.state.executionMode === 1 && (
                  <div>
                    <FormItem label="起止时间">
                      {getFieldDecorator('exStartDate', rules)(
                        <TimePicker format="HH" />
                      )}
                    </FormItem>
                    <FormItem>
                      {getFieldDecorator('exEndDate', rules)(
                        <TimePicker format="HH" />
                      )}
                    </FormItem>
                    <FormItem label="每隔">
                      {getFieldDecorator('timeNum', rules)(<InputNumber />)}
                    </FormItem>
                    <FormItem>
                      {getFieldDecorator('timeType', rules)(
                        <Select style={{ width: '80px' }}>
                          <Option key={1}>分</Option>
                          <Option key={2}>小时</Option>
                        </Select>
                      )}
                    </FormItem>
                  </div>
                )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) &&
                this.state.executionMode === 2 && (
                  <div>
                    <FormItem label="时间">
                      {getFieldDecorator('timeList', rules)(
                        <Input
                          placeholder="格式：19:05;14:20"
                          style={{ width: '300px' }}
                        />
                      )}
                    </FormItem>
                  </div>
                )}
              {this.state.executionType === 4 && (
                <div>
                  <FormItem label="指定">
                    {getFieldDecorator('monthType', rules)(
                      <RadioGroup
                        onChange={e =>
                          this.setState({
                            monthType: e.target.value
                          })
                        }
                      >
                        <Radio value={0}>最后一天</Radio>
                        <Radio value={1}>自定义</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                  {this.state.monthType === 1 && (
                    <FormItem label="每月">
                      {getFieldDecorator('monthDay', rules)(
                        <Select style={{ width: '80px' }}>
                          {Array.from(Array(31), (_, k) => k + 1).map(i => (
                            <Option key={i}>{i}</Option>
                          ))}
                        </Select>
                      )}
                      日
                    </FormItem>
                  )}
                </div>
              )}
            </div>
          </div>
        </Form>
        <div style={{ textAlign: 'center' }}>
          <Button onClick={() => history.goBack()}>返回</Button>
          &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          <Button type="primary" onClick={this.save}>
            保存
          </Button>
        </div>
      </div>
    )
  }
}

export default Form.create()(CreateTask)
